/**
 * 性能优化工具类
 */

// 防抖函数
export function debounce(func, wait, immediate = false) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      timeout = null
      if (!immediate) func.apply(this, args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(this, args)
  }
}

// 节流函数
export function throttle(func, limit) {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 内存管理
export class MemoryManager {
  constructor() {
    this.cache = new Map()
    this.maxSize = 1000
    this.cleanupInterval = 30000 // 30秒清理一次
    this.isRunning = false
    this.cleanupTimer = null
  }
  
  start() {
    if (this.isRunning) return
    this.isRunning = true
    this.startCleanup()
  }
  
  stop() {
    this.isRunning = false
    if (this.cleanupTimer) {
      clearInterval(this.cleanupTimer)
      this.cleanupTimer = null
    }
  }
  
  set(key, value) {
    if (this.cache.size >= this.maxSize) {
      // 删除最旧的缓存
      const firstKey = this.cache.keys().next().value
      this.cache.delete(firstKey)
    }
    this.cache.set(key, {
      value,
      timestamp: Date.now()
    })
  }
  
  get(key) {
    const item = this.cache.get(key)
    if (item) {
      item.timestamp = Date.now() // 更新访问时间
      return item.value
    }
    return null
  }
  
  clear() {
    this.cache.clear()
  }
  
  cleanup() {
    const now = Date.now()
    for (const [key, item] of this.cache.entries()) {
      if (now - item.timestamp > 300000) { // 5分钟未访问的缓存删除
        this.cache.delete(key)
      }
    }
  }
  
  startCleanup() {
    this.cleanupTimer = setInterval(() => {
      this.cleanup()
    }, this.cleanupInterval)
  }
  
  getStats() {
    return {
      cacheSize: this.cache.size,
      maxSize: this.maxSize,
      isRunning: this.isRunning
    }
  }
  
  reset() {
    this.clear()
  }
}

// 性能监控
export class PerformanceMonitor {
  constructor() {
    this.metrics = {
      renderTime: 0,
      memoryUsage: 0,
      messageCount: 0,
      scrollEvents: 0
    }
    this.observers = []
    this.isRunning = false
    this.monitoringInterval = null
  }
  
  start() {
    if (this.isRunning) return
    
    this.isRunning = true
    this.startMonitoring()
  }
  
  stop() {
    this.isRunning = false
    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval)
      this.monitoringInterval = null
    }
  }
  
  startMonitoring() {
    // 定期更新内存使用情况
    this.monitoringInterval = setInterval(() => {
      this.updateMemoryUsage()
    }, 5000) // 每5秒更新一次
  }
  
  startMeasure(name) {
    performance.mark(`${name}-start`)
  }
  
  endMeasure(name) {
    performance.mark(`${name}-end`)
    performance.measure(name, `${name}-start`, `${name}-end`)
    
    const measure = performance.getEntriesByName(name)[0]
    if (measure) {
      this.metrics.renderTime = Math.round(measure.duration)
    }
  }
  
  updateMemoryUsage() {
    if (performance.memory) {
      this.metrics.memoryUsage = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024)
    }
  }
  
  incrementCounter(counterName) {
    this.metrics[counterName] = (this.metrics[counterName] || 0) + 1
  }
  
  getMetrics() {
    return { ...this.metrics }
  }
  
  getReport() {
    return {
      metrics: this.getMetrics(),
      timestamp: Date.now(),
      isRunning: this.isRunning
    }
  }
  
  reset() {
    this.metrics = {
      renderTime: 0,
      memoryUsage: 0,
      messageCount: 0,
      scrollEvents: 0
    }
  }
}

// 图片懒加载
export class LazyImageLoader {
  constructor(options = {}) {
    this.options = {
      root: null,
      rootMargin: '50px',
      threshold: 0.1,
      ...options
    }
    this.observer = null
    this.init()
  }
  
  init() {
    if ('IntersectionObserver' in window) {
      this.observer = new IntersectionObserver(
        this.handleIntersection.bind(this),
        this.options
      )
    }
  }
  
  observe(img) {
    if (this.observer) {
      this.observer.observe(img)
    } else {
      // 降级处理
      this.loadImage(img)
    }
  }
  
  unobserve(img) {
    if (this.observer) {
      this.observer.unobserve(img)
    }
  }
  
  handleIntersection(entries) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        this.loadImage(entry.target)
        this.unobserve(entry.target)
      }
    })
  }
  
  loadImage(img) {
    const src = img.dataset.src
    if (src) {
      img.src = src
      img.classList.add('loaded')
    }
  }
  
  disconnect() {
    if (this.observer) {
      this.observer.disconnect()
    }
  }
}

// 虚拟滚动计算器
export class VirtualScrollCalculator {
  constructor(itemHeight, containerHeight, overscan = 5) {
    this.itemHeight = itemHeight
    this.containerHeight = containerHeight
    this.overscan = overscan
  }
  
  calculateVisibleRange(scrollTop, totalItems) {
    const startIndex = Math.floor(scrollTop / this.itemHeight)
    const visibleCount = Math.ceil(this.containerHeight / this.itemHeight)
    const endIndex = Math.min(startIndex + visibleCount, totalItems)
    
    return {
      startIndex: Math.max(0, startIndex - this.overscan),
      endIndex: Math.min(endIndex + this.overscan, totalItems),
      offsetY: startIndex * this.itemHeight
    }
  }
  
  getTotalHeight(totalItems) {
    return totalItems * this.itemHeight
  }
}

// 事件委托管理器
export class EventDelegateManager {
  constructor(container) {
    this.container = container
    this.handlers = new Map()
    this.init()
  }
  
  init() {
    this.container.addEventListener('click', this.handleClick.bind(this))
    this.container.addEventListener('mouseover', this.handleMouseOver.bind(this))
    this.container.addEventListener('mouseleave', this.handleMouseLeave.bind(this))
  }
  
  handleClick(event) {
    const target = event.target.closest('[data-action]')
    if (target) {
      const action = target.dataset.action
      const handler = this.handlers.get(action)
      if (handler) {
        handler(event, target)
      }
    }
  }
  
  handleMouseOver(event) {
    const target = event.target.closest('[data-message-id]')
    if (target) {
      const messageId = target.dataset.messageId
      const handler = this.handlers.get('message-enter')
      if (handler) {
        handler(messageId, event)
      }
    }
  }
  
  handleMouseLeave(event) {
    const handler = this.handlers.get('message-leave')
    if (handler) {
      handler(event)
    }
  }
  
  on(action, handler) {
    this.handlers.set(action, handler)
  }
  
  off(action) {
    this.handlers.delete(action)
  }
  
  destroy() {
    this.container.removeEventListener('click', this.handleClick)
    this.container.removeEventListener('mouseover', this.handleMouseOver)
    this.container.removeEventListener('mouseleave', this.handleMouseLeave)
    this.handlers.clear()
  }
}

// 批量更新管理器
export class BatchUpdateManager {
  constructor() {
    this.updates = new Set()
    this.isScheduled = false
  }
  
  addUpdate(update) {
    this.updates.add(update)
    this.scheduleUpdate()
  }
  
  scheduleUpdate() {
    if (!this.isScheduled) {
      this.isScheduled = true
      requestAnimationFrame(() => {
        this.flushUpdates()
        this.isScheduled = false
      })
    }
  }
  
  flushUpdates() {
    this.updates.forEach(update => update())
    this.updates.clear()
  }
}

// 导出单例实例
export const memoryManager = new MemoryManager()
export const performanceMonitor = new PerformanceMonitor()
export const batchUpdateManager = new BatchUpdateManager()
